// 全局变量
let homeworkList = [];
let currentFilter = 'all';
let isRecording = false;
let recognition = null;

// 作业分类关键词
const subjectKeywords = {
    '语文': ['语文', '作文', '阅读', '古诗', '课文', '字词', '拼音', '汉字', '背诵', '朗读', '写字', '日记'],
    '数学': ['数学', '计算', '应用题', '口算', '练习册', '题目', '算式', '加法', '减法', '乘法', '除法', '几何'],
    '英语': ['英语', '单词', '课文', '听力', '口语', '语法', '句子', 'ABC', '字母', '发音']
};

// 优先级关键词
const priorityKeywords = {
    'high': ['明天', '今天', '紧急', '重要', '考试', '测验', '必须', '赶紧'],
    'medium': ['这周', '周末', '下周', '作业'],
    'low': ['练习', '复习', '预习', '可选']
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

function initializeApp() {
    // 加载本地存储的作业
    loadHomeworkFromStorage();
    
    // 初始化语音识别
    initSpeechRecognition();
    
    // 绑定标签页切换事件
    bindTabEvents();
    
    // 绑定筛选按钮事件
    bindFilterEvents();
    
    // 更新统计信息
    updateStats();
    
    // 渲染作业列表
    renderHomeworkList();
    
    // iOS设备优化
    initIOSOptimizations();
}

// iOS设备优化
function initIOSOptimizations() {
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
    
    if (isIOS) {
        // 防止双击缩放
        document.addEventListener('touchstart', function(event) {
            if (event.touches.length > 1) {
                event.preventDefault();
            }
        });
        
        let lastTouchEnd = 0;
        document.addEventListener('touchend', function(event) {
            const now = (new Date()).getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, false);
        
        // 改善滚动性能
        document.body.style.webkitOverflowScrolling = 'touch';
        
        // 添加iOS状态栏适配
        if (window.navigator.standalone) {
            document.body.classList.add('standalone');
        }
        
        // 优化输入框焦点处理
        const inputs = document.querySelectorAll('input, textarea');
        inputs.forEach(input => {
            input.addEventListener('focus', function() {
                setTimeout(() => {
                    this.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }, 300);
            });
        });
    }
}

// 绑定标签页切换事件
function bindTabEvents() {
    const tabBtns = document.querySelectorAll('.tab-btn');
    const inputPanels = document.querySelectorAll('.input-panel');
    
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const targetTab = btn.dataset.tab;
            
            // 更新按钮状态
            tabBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            
            // 更新面板显示
            inputPanels.forEach(panel => {
                panel.classList.remove('active');
                if (panel.id === `${targetTab}-panel`) {
                    panel.classList.add('active');
                }
            });
        });
    });
}

// 绑定筛选按钮事件
function bindFilterEvents() {
    const filterBtns = document.querySelectorAll('.filter-btn');
    
    filterBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const filter = btn.dataset.filter;
            
            // 更新按钮状态
            filterBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            
            // 更新当前筛选
            currentFilter = filter;
            
            // 重新渲染列表
            renderHomeworkList();
        });
    });
}

// 从文字输入添加作业
function addHomeworkFromText() {
    const textInput = document.getElementById('text-input');
    const content = textInput.value.trim();
    
    if (!content) {
        alert('请输入作业内容！');
        return;
    }
    
    const homework = createHomeworkItem(content);
    addHomework(homework);
    
    // 清空输入框
    textInput.value = '';
}

// 创建作业项目
function createHomeworkItem(content) {
    const subject = classifySubject(content);
    const priority = classifyPriority(content);
    
    return {
        id: Date.now() + Math.random(),
        content: content,
        subject: subject,
        priority: priority,
        completed: false,
        createdAt: new Date().toISOString()
    };
}

// 智能分类学科
function classifySubject(content) {
    for (const [subject, keywords] of Object.entries(subjectKeywords)) {
        for (const keyword of keywords) {
            if (content.includes(keyword)) {
                return subject;
            }
        }
    }
    return '其他';
}

// 智能分类优先级
function classifyPriority(content) {
    for (const [priority, keywords] of Object.entries(priorityKeywords)) {
        for (const keyword of keywords) {
            if (content.includes(keyword)) {
                return priority;
            }
        }
    }
    return 'medium';
}

// 添加作业到列表
function addHomework(homework) {
    homeworkList.push(homework);
    saveHomeworkToStorage();
    updateStats();
    renderHomeworkList();
    
    // 显示成功提示
    showNotification('作业添加成功！', 'success');
}

// 切换作业完成状态
function toggleHomework(id) {
    const homework = homeworkList.find(h => h.id === id);
    if (homework) {
        homework.completed = !homework.completed;
        saveHomeworkToStorage();
        updateStats();
        renderHomeworkList();
        
        const message = homework.completed ? '作业标记为已完成！' : '作业标记为未完成！';
        showNotification(message, 'success');
    }
}

// 删除作业
function deleteHomework(id) {
    if (confirm('确定要删除这个作业吗？')) {
        homeworkList = homeworkList.filter(h => h.id !== id);
        saveHomeworkToStorage();
        updateStats();
        renderHomeworkList();
        showNotification('作业删除成功！', 'success');
    }
}

// 清空所有作业
function clearAllHomework() {
    if (confirm('确定要清空所有作业吗？此操作不可恢复！')) {
        homeworkList = [];
        saveHomeworkToStorage();
        updateStats();
        renderHomeworkList();
        showNotification('所有作业已清空！', 'success');
    }
}

// 渲染作业列表
function renderHomeworkList() {
    const listContainer = document.getElementById('homework-list');
    
    // 筛选作业
    let filteredHomework = homeworkList;
    if (currentFilter !== 'all') {
        filteredHomework = homeworkList.filter(h => h.subject === currentFilter);
    }
    
    // 排序：未完成的在前，按优先级和创建时间排序
    filteredHomework.sort((a, b) => {
        if (a.completed !== b.completed) {
            return a.completed ? 1 : -1;
        }
        
        const priorityOrder = { 'high': 0, 'medium': 1, 'low': 2 };
        if (a.priority !== b.priority) {
            return priorityOrder[a.priority] - priorityOrder[b.priority];
        }
        
        return new Date(b.createdAt) - new Date(a.createdAt);
    });
    
    if (filteredHomework.length === 0) {
        listContainer.innerHTML = `
            <div class="empty-state">
                <span class="emoji">📝</span>
                <p>还没有作业哦！快来添加第一个作业吧~</p>
            </div>
        `;
        return;
    }
    
    listContainer.innerHTML = filteredHomework.map(homework => `
        <div class="homework-item ${homework.completed ? 'completed' : ''}">
            <div class="homework-header">
                <span class="homework-subject">${homework.subject}</span>
                <span class="homework-priority priority-${homework.priority}">
                    ${getPriorityText(homework.priority)}
                </span>
            </div>
            <div class="homework-content">${homework.content}</div>
            <div class="homework-actions">
                <button class="complete-btn ${homework.completed ? 'completed' : ''}" 
                        onclick="toggleHomework(${homework.id})">
                    ${homework.completed ? '✅ 已完成' : '⭕ 标记完成'}
                </button>
                <div>
                    <span class="homework-time">${formatTime(homework.createdAt)}</span>
                    <button class="delete-btn" onclick="deleteHomework(${homework.id})">
                        🗑️ 删除
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

// 获取优先级文本
function getPriorityText(priority) {
    const texts = {
        'high': '🔴 高优先级',
        'medium': '🟡 中优先级',
        'low': '🟢 低优先级'
    };
    return texts[priority] || '🟡 中优先级';
}

// 格式化时间
function formatTime(isoString) {
    const date = new Date(isoString);
    const now = new Date();
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);
    
    if (diffMins < 1) return '刚刚';
    if (diffMins < 60) return `${diffMins}分钟前`;
    if (diffHours < 24) return `${diffHours}小时前`;
    if (diffDays < 7) return `${diffDays}天前`;
    
    return date.toLocaleDateString('zh-CN');
}

// 更新统计信息
function updateStats() {
    const total = homeworkList.length;
    const completed = homeworkList.filter(h => h.completed).length;
    const remaining = total - completed;
    
    document.getElementById('total-count').textContent = total;
    document.getElementById('completed-count').textContent = completed;
    document.getElementById('remaining-count').textContent = remaining;
}

// 本地存储相关
function saveHomeworkToStorage() {
    localStorage.setItem('homeworkList', JSON.stringify(homeworkList));
}

function loadHomeworkFromStorage() {
    const stored = localStorage.getItem('homeworkList');
    if (stored) {
        homeworkList = JSON.parse(stored);
    }
}

// 语音识别相关
function initSpeechRecognition() {
    // 检测iOS设备
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
    const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        recognition = new SpeechRecognition();
        
        recognition.continuous = false;
        recognition.interimResults = false;
        recognition.lang = 'zh-CN';
        
        // iOS设备特殊配置
        if (isIOS) {
            recognition.maxAlternatives = 1;
        }
        
        recognition.onstart = function() {
            document.getElementById('voice-status').textContent = '正在录音，请说话...';
            // iOS设备震动反馈
            if (navigator.vibrate) {
                navigator.vibrate(100);
            }
        };
        
        recognition.onresult = function(event) {
            const result = event.results[0][0].transcript;
            document.getElementById('voice-result').innerHTML = `
                <strong>识别结果：</strong>${result}<br>
                <button class="add-btn" onclick="addHomeworkFromVoice('${result.replace(/'/g, "\\'")}')">➕ 添加这个作业</button>
            `;
            // iOS设备震动反馈
            if (navigator.vibrate) {
                navigator.vibrate([100, 50, 100]);
            }
        };
        
        recognition.onerror = function(event) {
            let errorMessage = '语音识别出错，请重试';
            if (event.error === 'not-allowed') {
                errorMessage = '请允许麦克风权限后重试';
            } else if (event.error === 'no-speech') {
                errorMessage = '没有检测到语音，请重试';
            } else if (event.error === 'network') {
                errorMessage = '网络错误，请检查网络连接';
            }
            document.getElementById('voice-status').textContent = errorMessage;
            console.error('语音识别错误:', event.error);
        };
        
        recognition.onend = function() {
            isRecording = false;
            const voiceBtn = document.getElementById('voice-btn');
            voiceBtn.textContent = '🎤 点击开始录音';
            voiceBtn.classList.remove('recording');
            document.getElementById('voice-status').textContent = '录音结束';
        };
    } else {
        // 为iOS Safari提供特殊提示
        if (isIOS && isSafari) {
            document.getElementById('voice-status').textContent = 'iOS Safari需要HTTPS环境才能使用语音功能';
        } else {
            document.getElementById('voice-status').textContent = '您的浏览器不支持语音识别功能';
        }
    }
}

function toggleVoiceRecording() {
    if (!recognition) {
        alert('语音识别功能不可用');
        return;
    }
    
    const voiceBtn = document.getElementById('voice-btn');
    
    if (isRecording) {
        recognition.stop();
    } else {
        recognition.start();
        isRecording = true;
        voiceBtn.textContent = '🛑 点击停止录音';
        voiceBtn.classList.add('recording');
        document.getElementById('voice-result').innerHTML = '';
    }
}

function addHomeworkFromVoice(content) {
    const homework = createHomeworkItem(content);
    addHomework(homework);
    document.getElementById('voice-result').innerHTML = '';
}

// 图片上传和OCR识别
function handleImageUpload(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    // 检查文件大小（iOS设备内存限制）
    const maxSize = 5 * 1024 * 1024; // 5MB
    if (file.size > maxSize) {
        alert('图片文件过大，请选择小于5MB的图片');
        return;
    }
    
    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/heic', 'image/heif'];
    if (!allowedTypes.includes(file.type)) {
        alert('请选择JPG、PNG或HEIC格式的图片');
        return;
    }
    
    // 显示图片预览
    const reader = new FileReader();
    reader.onload = function(e) {
        document.getElementById('image-preview').innerHTML = `
            <img src="${e.target.result}" alt="上传的图片" style="touch-action: manipulation;">
        `;
        
        // iOS设备震动反馈
        if (navigator.vibrate) {
            navigator.vibrate(50);
        }
        
        // 模拟OCR识别（实际项目中需要调用OCR API）
        simulateOCR(e.target.result);
    };
    
    reader.onerror = function() {
        alert('图片读取失败，请重试');
    };
    
    reader.readAsDataURL(file);
}

// 模拟OCR文字识别
function simulateOCR(imageSrc) {
    // 这里模拟OCR识别过程
    document.getElementById('image-result').innerHTML = `
        <p><strong>正在识别图片中的文字...</strong></p>
        <div style="margin-top: 10px;">
            <p>💡 提示：由于这是演示版本，请手动输入图片中的作业内容。</p>
            <textarea id="ocr-input" placeholder="请输入图片中的作业内容..." style="width: 100%; height: 80px; margin: 10px 0; padding: 10px; border: 1px solid #ddd; border-radius: 5px;"></textarea>
            <button class="add-btn" onclick="addHomeworkFromOCR()">➕ 添加识别的作业</button>
        </div>
    `;
}

function addHomeworkFromOCR() {
    const ocrInput = document.getElementById('ocr-input');
    const content = ocrInput.value.trim();
    
    if (!content) {
        alert('请输入作业内容！');
        return;
    }
    
    const homework = createHomeworkItem(content);
    addHomework(homework);
    
    // 清空相关内容
    document.getElementById('image-preview').innerHTML = '';
    document.getElementById('image-result').innerHTML = '';
    document.getElementById('image-input').value = '';
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#48bb78' : '#667eea'};
        color: white;
        padding: 15px 20px;
        border-radius: 10px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        z-index: 1000;
        animation: slideInRight 0.3s ease;
    `;
    notification.textContent = message;
    
    // 添加动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideInRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
    `;
    document.head.appendChild(style);
    
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        notification.style.animation = 'slideInRight 0.3s ease reverse';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}